package hy.service.impl;

import hy.bean.User;
import hy.dao.UserDao;
import hy.service.UserService;
import hy.util.PassUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao dao;
    @Override
    public void regist(User u) {
        String salt = PassUtil.randomSalt();
        u.setPass(PassUtil.encode(u.getPass(),salt));
        u.setSalt(salt);
        dao.insert(u);
    }

    @Override
    public String login(User u) {
       //handle(u);
        UsernamePasswordToken t = new UsernamePasswordToken(u.getName(),u.getPass());
        Subject sub = SecurityUtils.getSubject();
        String err=null;
        try{
            //调用realm中的doGetAuthen,如果是sub.hasRole("manager")则会调用realm中的doGetAuthor
            sub.login(t);
        }catch (AuthenticationException e){
            e.printStackTrace();
            err = "用户名或密码错误";
        }
        return err;
    }
}
